<template>
  <div class="game-entertainment-page">
    <van-nav-bar
      title="游戏娱乐"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    />

    <div class="feature-intro">
      <div class="intro-content">
        <div class="intro-icon">🎮</div>
        <div class="intro-text">
          <h3>AI游戏娱乐</h3>
          <p>语音游戏互动，寓教于乐</p>
        </div>
      </div>
    </div>

    <div class="games-container">
      <div class="games-grid">
        <div
          v-for="game in games"
          :key="game.id"
          class="game-card"
          @click="startGame(game)"
        >
          <div class="game-icon">{{ game.icon }}</div>
          <div class="game-info">
            <h4>{{ game.name }}</h4>
            <p>{{ game.description }}</p>
          </div>
        </div>
      </div>

      <div v-if="currentGame" class="game-area">
        <div class="game-header">
          <h3>{{ currentGame.name }}</h3>
          <div class="game-actions">
            <van-button size="small" @click="showStats = !showStats">统计</van-button>
            <van-button size="small" @click="resetGame">重置</van-button>
            <van-button size="small" @click="endGame">结束</van-button>
          </div>
        </div>

        <!-- 游戏配置 -->
        <div class="game-config">
          <div class="config-row">
            <span class="config-label">难度:</span>
            <van-radio-group v-model="gameConfig.difficulty" direction="horizontal">
              <van-radio name="easy">简单</van-radio>
              <van-radio name="normal">普通</van-radio>
              <van-radio name="hard">困难</van-radio>
            </van-radio-group>
          </div>
          <div class="config-row">
            <span class="config-label">题数:</span>
            <van-stepper v-model="gameConfig.maxQuestions" min="5" max="20" />
          </div>
          <div class="config-row">
            <span class="config-label">提示:</span>
            <van-switch v-model="gameConfig.enableHints" />
          </div>
          <div class="config-row">
            <span class="config-label">随机:</span>
            <van-switch v-model="gameConfig.randomMode" />
            <span class="config-hint">开启后AI会随机生成内容</span>
          </div>
        </div>

        <!-- 游戏状态显示 -->
        <div v-if="gameSession" class="game-status">
          <div class="status-item">
            <span class="status-label">等级:</span>
            <span class="status-value">{{ gameSession.level }}级</span>
          </div>
          <div class="status-item">
            <span class="status-label">得分:</span>
            <span class="status-value">{{ gameSession.score }}分</span>
          </div>
          <div class="status-item">
            <span class="status-label">连胜:</span>
            <span class="status-value">{{ gameSession.winStreak }}次</span>
          </div>
          <div v-if="gameSession.config?.enableHints" class="status-item">
            <span class="status-label">提示:</span>
            <span class="status-value">{{ gameSession.config.hintsRemaining }}次</span>
            <van-button size="mini" @click="useHint" :disabled="gameSession.config.hintsRemaining <= 0">
              使用提示
            </van-button>
          </div>
        </div>

        <!-- 游戏统计 -->
        <div v-if="showStats && gameSession?.stats" class="game-stats">
          <h4>📊 游戏统计</h4>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">总题数:</span>
              <span class="stat-value">{{ gameSession.stats.totalQuestions }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">正确数:</span>
              <span class="stat-value">{{ gameSession.stats.correctAnswers }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">准确率:</span>
              <span class="stat-value">{{ gameSession.stats.accuracyRate?.toFixed(1) }}%</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">平均用时:</span>
              <span class="stat-value">{{ (gameSession.stats.averageResponseTime / 1000)?.toFixed(1) }}秒</span>
            </div>
          </div>
        </div>

        <div class="game-content">
          <div v-if="gameMessages.length > 0" class="game-messages" ref="messagesContainer">
            <div
              v-for="(message, index) in gameMessages"
              :key="index"
              :class="['game-message', message.type]"
            >
              {{ message.content }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 固定在底部的输入框 -->
    <div v-if="currentGame" class="fixed-input-container">
      <div class="game-input">
        <van-field
          v-model="gameInput"
          :placeholder="getInputPlaceholder()"
          @keyup.enter="sendGameInput"
        />
        <van-button
          type="primary"
          :loading="isLoading"
          @click="sendGameInput"
        >
          发送
        </van-button>
      </div>
    </div>

    <!-- 为固定输入框预留空间 -->
    <div v-if="currentGame" class="input-spacer"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { showToast } from 'vant'
import aiService from '@/services/aiService'

const currentGame = ref<any>(null)
const gameInput = ref('')
const gameMessages = ref<Array<{
  type: 'user' | 'ai'
  content: string
}>>([])
const isLoading = ref(false)
const gameSession = ref<any>(null)
const showStats = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)

// 游戏配置
const gameConfig = ref({
  difficulty: 'normal',
  maxQuestions: 10,
  enableHints: true,
  randomMode: true // 随机模式，让AI随机生成内容
})

const games = ref([
  {
    id: 'riddle',
    name: '猜谜语',
    description: '我出谜语你来猜',
    icon: '🤔'
  },
  {
    id: 'idiom',
    name: '成语接龙',
    description: '成语接龙挑战',
    icon: '📚'
  },
  {
    id: 'story',
    name: '故事接龙',
    description: '一起编故事',
    icon: '📖'
  },
  {
    id: 'quiz',
    name: '知识问答',
    description: '趣味知识竞赛',
    icon: '🧠'
  }
])

const startGame = async (game: any) => {
  currentGame.value = game
  gameMessages.value = []

  try {
    // 获取或创建游戏会话
    const sessionResponse = await aiService.getGameSession(12345, game.id)
    if (sessionResponse.code === 200) {
      gameSession.value = sessionResponse.data
    }

    // 游戏开始消息
    const startMessage = getStartMessage(game.id)
    let welcomeMessage = `🎮 ${startMessage}\n\n📊 游戏状态:\n等级: ${gameSession.value?.level || 1}级\n得分: ${gameSession.value?.score || 0}分\n连胜: ${gameSession.value?.winStreak || 0}次`

    // 如果有游戏历史，显示恢复信息
    if (gameSession.value?.stats?.totalQuestions > 0) {
      welcomeMessage += `\n\n🔄 检测到游戏进度，继续第${gameSession.value.stats.totalQuestions + 1}轮游戏\n已完成: ${gameSession.value.stats.totalQuestions}题\n正确率: ${gameSession.value.stats.accuracyRate?.toFixed(1)}%`
    }

    gameMessages.value.push({
      type: 'ai',
      content: welcomeMessage
    })

    // 自动开始第一轮游戏
    await sendMessage('开始游戏', 'start')
  } catch (error) {
    console.error('启动游戏失败:', error)
    showToast('游戏启动失败')
  }
}

const endGame = () => {
  currentGame.value = null
  gameMessages.value = []
  gameInput.value = ''
  gameSession.value = null
  showStats.value = false
}

// 重置游戏
const resetGame = async () => {
  if (!currentGame.value) return

  try {
    const response = await aiService.resetGameSession(12345, currentGame.value.id)
    if (response.code === 200) {
      gameSession.value = response.data
      gameMessages.value = []
      gameInput.value = ''
      showToast('游戏已重置')

      // 重新开始游戏
      await startGame(currentGame.value)
    } else {
      showToast('重置失败')
    }
  } catch (error) {
    console.error('重置游戏失败:', error)
    showToast('重置失败')
  }
}

// 使用提示
const useHint = async () => {
  if (!currentGame.value || !gameSession.value) return

  try {
    const response = await aiService.useGameHint(12345, currentGame.value.id)
    if (response.code === 200 && response.data.success) {
      gameSession.value.config.hintsRemaining = response.data.hintsRemaining
      showToast('提示已使用，请查看AI回复')

      // 发送提示请求
      await sendMessage('请给我一个提示', 'playing')
    } else {
      showToast(response.data?.message || '没有可用的提示')
    }
  } catch (error) {
    console.error('使用提示失败:', error)
    showToast('使用提示失败')
  }
}

// 发送消息的辅助方法
const sendMessage = async (userInput: string, gameState: string = 'playing') => {
  if (!userInput.trim() || !currentGame.value) return

  // 只有非开始状态才添加用户消息
  if (gameState !== 'start') {
    gameMessages.value.push({
      type: 'user',
      content: userInput
    })
  }

  isLoading.value = true

  // 添加AI消息占位符
  const aiMessageIndex = gameMessages.value.length
  gameMessages.value.push({
    type: 'ai',
    content: ''
  })

  let accumulatedText = ''

  try {
    console.log('🚀 开始流式游戏:', currentGame.value.id, userInput, gameState)

    // 使用流式输出
    await aiService.gameEntertainmentStream(
      12345,
      currentGame.value.id,
      userInput,
      gameState,
      gameConfig.value.difficulty,
      gameConfig.value.maxQuestions,
      gameConfig.value.enableHints,
      gameConfig.value.randomMode,
      // onMessage回调
      (content: string) => {
        console.log('📝 收到游戏内容:', content)
        accumulatedText += content
        gameMessages.value[aiMessageIndex].content = accumulatedText
      },
      // onComplete回调
      async () => {
        console.log('✅ 流式游戏完成')
        isLoading.value = false
        // 更新游戏会话信息
        try {
          const sessionResponse = await aiService.getGameSession(12345, currentGame.value.id)
          if (sessionResponse.code === 200) {
            gameSession.value = sessionResponse.data
          }
        } catch (error) {
          console.error('更新游戏会话失败:', error)
        }
      },
      // onError回调
      async (error: any) => {
        console.error('流式输出失败，尝试非流式输出:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.gameEntertainment(12345, currentGame.value.id, userInput, gameState,
            gameConfig.value.difficulty, gameConfig.value.maxQuestions, gameConfig.value.enableHints, gameConfig.value.randomMode)
          console.log('📊 非流式游戏API响应:', response)

          if (response && response.code === 200) {
            // 智能解析数据格式
            let content = ''
            if (response.data) {
              if (typeof response.data === 'string') {
                content = response.data
              } else if (response.data.text) {
                content = response.data.text
              } else if (response.data.response) {
                content = response.data.response
              } else if (response.data.content) {
                content = response.data.content
              } else {
                content = JSON.stringify(response.data, null, 2)
              }
            }

            gameMessages.value[aiMessageIndex].content = content || '游戏继续进行中...'

            // 更新游戏会话信息
            if (response.data?.gameSession) {
              gameSession.value = response.data.gameSession
            }
          } else {
            gameMessages.value[aiMessageIndex].content = `游戏API调用失败: ${response?.message || '未知错误'}`
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          gameMessages.value[aiMessageIndex].content = '游戏出现了小问题，让我们继续吧！'
        }

        isLoading.value = false
      }
    )

  } catch (error) {
    console.error('游戏娱乐失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.gameEntertainment(12345, currentGame.value.id, userInput, gameState,
        gameConfig.value.difficulty, gameConfig.value.maxQuestions, gameConfig.value.enableHints, gameConfig.value.randomMode)
      console.log('📊 备选游戏API响应:', response)

      if (response && response.code === 200) {
        // 智能解析数据格式
        let content = ''
        if (response.data) {
          if (typeof response.data === 'string') {
            content = response.data
          } else if (response.data.text) {
            content = response.data.text
          } else if (response.data.response) {
            content = response.data.response
          } else if (response.data.content) {
            content = response.data.content
          } else {
            content = JSON.stringify(response.data, null, 2)
          }
        }

        gameMessages.value[aiMessageIndex].content = content || '游戏继续进行中...'

        // 更新游戏会话信息
        if (response.data?.gameSession) {
          gameSession.value = response.data.gameSession
        }
      } else {
        gameMessages.value[aiMessageIndex].content = `备选游戏API调用失败: ${response?.message || '未知错误'}`
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      gameMessages.value[aiMessageIndex].content = `最终错误: ${fallbackError.message || fallbackError}\n\n请检查网络连接或联系技术支持。`
    }

    isLoading.value = false
  }
}

const getStartMessage = (gameId: string) => {
  const messages = {
    riddle: '欢迎来到谜语挑战！AI会随机出一些有趣的谜语，每次都不一样，看看你能猜对多少！',
    idiom: '成语接龙开始！AI会随机选择一个成语作为开头，我们轮流接龙，保持游戏的新鲜感！',
    story: '故事接龙游戏！AI会随机创作一个故事开头，然后我们一起续写精彩的故事！',
    quiz: '知识问答时间！AI会随机出不同领域的选择题，每次都有新的挑战等着你！'
  }
  return messages[gameId] || '游戏开始！'
}

const getInputPlaceholder = () => {
  if (!currentGame.value) return ''

  const placeholders = {
    riddle: '输入你的答案...',
    idiom: '输入成语...',
    story: '继续故事...',
    quiz: '输入答案...'
  }
  return placeholders[currentGame.value.id] || '输入内容...'
}

const sendGameInput = async () => {
  if (!gameInput.value.trim() || !currentGame.value) return

  gameMessages.value.push({
    type: 'user',
    content: gameInput.value
  })

  const userInput = gameInput.value
  gameInput.value = ''
  isLoading.value = true

  // 添加AI消息占位符
  const aiMessageIndex = gameMessages.value.length
  gameMessages.value.push({
    type: 'ai',
    content: ''
  })

  let accumulatedText = ''

  try {
    // 使用流式输出
    await aiService.gameEntertainmentStream(
      12345,
      currentGame.value.id,
      userInput,
      'playing',
      gameConfig.value.difficulty,
      gameConfig.value.maxQuestions,
      gameConfig.value.enableHints,
      gameConfig.value.randomMode,
      // onMessage回调
      (content: string) => {
        accumulatedText += content
        gameMessages.value[aiMessageIndex].content = accumulatedText
      },
      // onComplete回调
      async () => {
        isLoading.value = false
        // 更新游戏会话信息
        try {
          const sessionResponse = await aiService.getGameSession(12345, currentGame.value.id)
          if (sessionResponse.code === 200) {
            gameSession.value = sessionResponse.data
          }
        } catch (error) {
          console.error('更新游戏会话失败:', error)
        }
      },
      // onError回调
      async (error: any) => {
        console.error('流式输出失败，尝试非流式输出:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.gameEntertainment(12345, currentGame.value.id, userInput, 'playing',
            gameConfig.value.difficulty, gameConfig.value.maxQuestions, gameConfig.value.enableHints, gameConfig.value.randomMode)
          if (response.code === 200) {
            gameMessages.value[aiMessageIndex].content = response.data?.text || response.data?.response || '游戏继续进行中...'
            // 更新游戏会话信息
            if (response.data?.gameSession) {
              gameSession.value = response.data.gameSession
            }
          } else {
            gameMessages.value[aiMessageIndex].content = '游戏出现了小问题，让我们继续吧！'
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          gameMessages.value[aiMessageIndex].content = '游戏出现了小问题，让我们继续吧！'
        }

        isLoading.value = false
      }
    )

  } catch (error) {
    console.error('游戏娱乐失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.gameEntertainment(12345, currentGame.value.id, userInput, 'playing',
        gameConfig.value.difficulty, gameConfig.value.maxQuestions, gameConfig.value.enableHints, gameConfig.value.randomMode)
      if (response.code === 200) {
        gameMessages.value[aiMessageIndex].content = response.data?.text || response.data?.response || '游戏继续进行中...'
        // 更新游戏会话信息
        if (response.data?.gameSession) {
          gameSession.value = response.data.gameSession
        }
      } else {
        gameMessages.value[aiMessageIndex].content = '游戏出现了小问题，让我们继续吧！'
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      gameMessages.value[aiMessageIndex].content = '游戏出现了小问题，让我们继续吧！'
    }

    isLoading.value = false
  }
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动
watch(gameMessages, () => {
  scrollToBottom()
}, { deep: true })
</script>

<style scoped>
.game-entertainment-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  padding-bottom: 100px; /* 为固定输入框预留空间 */
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.feature-intro {
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.intro-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.intro-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 154, 158, 0.1);
  border-radius: 16px;
}

.intro-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.intro-text p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.games-container {
  padding: 16px;
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.game-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.game-card:hover {
  transform: translateY(-2px);
}

.game-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.game-info h4 {
  margin: 0 0 4px 0;
  color: #2c3e50;
}

.game-info p {
  margin: 0;
  font-size: 12px;
  color: #7f8c8d;
}

.game-area {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.game-header h3 {
  margin: 0;
  color: #2c3e50;
}

.game-actions {
  display: flex;
  gap: 8px;
}

.game-config {
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border-left: 4px solid #ff6b6b;
}

.config-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.config-row:last-child {
  margin-bottom: 0;
}

.config-label {
  color: #666;
  font-weight: 500;
  min-width: 60px;
}

.config-hint {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

.game-status {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border-left: 4px solid #1989fa;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.status-label {
  color: #666;
  font-weight: 500;
}

.status-value {
  color: #1989fa;
  font-weight: bold;
}

.game-stats {
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border-left: 4px solid #07c160;
}

.game-stats h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
}

.stat-label {
  color: #666;
  font-size: 13px;
}

.stat-value {
  color: #07c160;
  font-weight: bold;
  font-size: 14px;
}

.game-messages {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.game-message {
  padding: 8px 12px;
  margin-bottom: 8px;
  border-radius: 12px;
  font-size: 14px;
}

.game-message.user {
  background: #e3f2fd;
  text-align: right;
}

.game-message.ai {
  background: #f3e5f5;
}

.game-input {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

/* 固定输入框样式 */
.fixed-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  padding: 12px 16px;
  z-index: 1000;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  animation: slideUp 0.3s ease-out;
}

.fixed-input-container .game-input {
  max-width: 600px;
  margin: 0 auto;
}

.fixed-input-container .van-field {
  flex: 1;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.9);
}

.fixed-input-container .van-button {
  border-radius: 20px;
  min-width: 60px;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 为固定输入框预留空间 */
.input-spacer {
  height: 80px;
}

/* 调整游戏消息区域，避免被固定输入框遮挡 */
.game-messages {
  max-height: calc(50vh - 100px);
  overflow-y: auto;
  margin-bottom: 16px;
  padding-bottom: 20px;
}
</style>
